package org.tgcloud.group.core.WXServiceUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author: zhy
 * @create: 2023-12-31 09:13
 * @description: 签名工具类
 */
public class SignUtil {

    /**
     * 前端jssdk页面配置需要用到的配置参数
     * @param url
     * @return {appid,timestamp,nonceStr,signature}
     * @throws Exception
     */

    public static HashMap jsSDK_Sign(String url) throws Exception {
        String nonce_str = create_nonce_str();
        String timestamp= System.currentTimeMillis()/1000 + "";
        String jsapi_ticket= WxService.getJsSdkTicket();
// 注意这里参数名必须全部小写，且必须有序
// 参数
        Map packageParams = new HashMap<>();
        packageParams.put("url", url);
        packageParams.put("noncestr", nonce_str);
        packageParams.put("jsapi_ticket", jsapi_ticket);
        packageParams.put("timestamp", timestamp);
// 获得拼接好的参数,按照ASCLL大小排序
        String createLinkString = createLinkString(packageParams);
        String signature = SHA1(createLinkString);
// 参数封装,返回前台
        HashMap jssdk=new HashMap();
        jssdk.put("appId", WxService.APP_ID);
        jssdk.put("timestamp", timestamp);
        jssdk.put("nonceStr", nonce_str);
        jssdk.put("signature", signature);
        return jssdk;
    }

    public static String SHA1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
// Create Hex String
            StringBuffer hexString = new StringBuffer();
// 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map params) {
        List keys = new ArrayList(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = (String) keys.get(i);
            String value = (String) params.get(key);
            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
        return prestr;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }


}
